#pragma once
#include <iostream>
#include <vector>
#include <semaphore.h>
#include <pthread.h>
template <class T>
class ringqueue
{
    const static int defaultcap = 5;
    void P(sem_t &sem)
    {
        sem_wait(&sem);
    }
    void V(sem_t &sem)
    {
        sem_post(&sem);
    }
    void Lock(pthread_mutex_t &mutex)
    {
        pthread_mutex_lock(&mutex);
    }
    void Unlock(pthread_mutex_t &mutex)
    {
        pthread_mutex_unlock(&mutex);
    }

public:
    ringqueue(int cap = defaultcap) : ringqueue_(cap), cap_(cap), c_index_(0), p_index_(0)
    {
        sem_init(&cdata_, 0, 0);
        sem_init(&pspace_, 0, cap);
        pthread_mutex_init(&c_mutex_, nullptr);
        pthread_mutex_init(&p_mutex_, nullptr);
    }
    void Push(const T &in)
    {
        P(pspace_);

        Lock(p_mutex_);
        ringqueue_[p_index_] = in;
        p_index_++;
        p_index_ %= cap_;
        Unlock(p_mutex_);

        V(cdata_);
    }
    void Pop(T *out)
    {
        P(cdata_);

        Lock(c_mutex_);
        *out = ringqueue_[c_index_];
        c_index_++;
        c_index_ %= cap_;
        Unlock(c_mutex_);

        V(pspace_);
    }
    ~ringqueue()
    {
        sem_destroy(&cdata_);
        sem_destroy(&pspace_);
        pthread_mutex_destroy(&c_mutex_);
        pthread_mutex_destroy(&p_mutex_);
    }

private:
    std::vector<T> ringqueue_;
    int cap_;
    int c_index_;
    int p_index_;
    sem_t cdata_;
    sem_t pspace_;
    pthread_mutex_t c_mutex_;
    pthread_mutex_t p_mutex_;
};